package com.op.teachingliteapp.sender.ui;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.sender.Runtime;
import com.op.teachingliteapp.sender.runnable.DeviceScanRunnable;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class DeviceScanDialog {
	private static AlertDialog alertDialog = null;
	  private static ArrayAdapter<DeviceDisplay> listAdapter ;
    private  static Context context;

    public  DeviceScanDialog( Context context) {
        this.context =context;
    }

    public static AlertDialog getDialog() {
		if (alertDialog == null) {

			LayoutInflater layoutInflater = LayoutInflater.from(context);
			View view = layoutInflater.inflate(R.layout.device_scan_dialog,
					null);
			Button button = (Button) view.findViewById(R.id.get_devices);
			ListView deviceListView = (ListView) view
					.findViewById(R.id.device_list);

			listAdapter  = new ArrayAdapter<DeviceDisplay>(
					context, android.R.layout.simple_expandable_list_item_1);
			deviceListView.setAdapter(listAdapter);
			button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
                    listAdapter.clear();
					  new Thread(new DeviceScanRunnable(listAdapter)).start();

				}
			});

			alertDialog = new AlertDialog.Builder(context).setView(view)
					.create();
			
			deviceListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					DeviceDisplay deviceDisplay = listAdapter.getItem(position);
					Runtime.ip =deviceDisplay.getIp();
                    alertDialog.cancel();
					
				}
			});
			

		}

		return alertDialog;

	}

}
